package com.well.kernel.spring.jdbc;

import com.well.kernel.spring.jdbc.annotation.DataSource;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * Copyright &copy; Well All rights reserved.
 * Author:Well
 * Date:2017-10-25
 * Description:数据源切面
 * 如果使用 com.well.kernel.spring.jdbc.annotation.DataSource 注解，调用时会切换到指定的数据源
 */


@Order(1)
@Aspect
@Component
public class DataSourceAspect {

    private static Logger logger=Logger.getLogger(DataSourceAspect.class);

    @Around("@annotation(dataSource)")
    public Object doAround(ProceedingJoinPoint pjp, DataSource dataSource) {
        Object result = null;
        boolean selectedDataSource = false;
        try {
            if (null != dataSource) {
                selectedDataSource = true;
                if (dataSource.slave()) {
                    DynamicDataSource.useSlave();
                } else {
                    DynamicDataSource.useMaster();
                }
            }
            result = pjp.proceed();
        } catch (Throwable e) {
            throw new RuntimeException("数据源切换错误", e);
        } finally {
            if (selectedDataSource) {
                DynamicDataSource.reset();
            }
        }
        return result;
    }

}
